package com.itboye.lottery.retrofit;

import android.util.Log;

import com.itboye.lottery.BuildConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;

public class LogInterceptor implements Interceptor {

    public static String TAG = "LogInterceptor";

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        //打印retrofit日志
//        Pattern pattern = Pattern.compile("(\\u(\p{XDigit}{4}))");
//        Matcher matcher = pattern.matcher(message);
//        char ch;
//        while (matcher.find()) {
//            ch = (char) Integer.parseInt(matcher.group(2), 16);
//            message = message.replace(matcher.group(1), ch + "");
        if (BuildConfig.IS_DEBUG) {
            Log.d(TAG, " ");
            Log.d(TAG, " ");
            Log.d(TAG, " ");
            Log.d(TAG, "----------Start----------------");
            Log.d(TAG, "| " + request.toString());
            String method = request.method();
            if ("POST".equals(method)) {
                StringBuilder sb = new StringBuilder();
                if (request.body() instanceof FormBody) {
                    FormBody body = (FormBody) request.body();
                    for (int i = 0; i < body.size(); i++) {
                        sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                    }
                    sb.delete(sb.length() - 1, sb.length());
                    Log.d(TAG, "| RequestParams:{" + URLDecoder.decode(sb.toString(), "utf-8") + "}");
                } else if (request.body() instanceof RequestBody) {
                    Iterator<String> iterator = response.request().url().queryParameterNames().iterator();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        String value = response.request().url().queryParameter(key);
                        sb.append(key + "=" + value + "&");
                    }
                    if (sb.length() > 0) {
                        sb.delete(sb.length() - 1, sb.length());
                    }
                    Log.d(TAG, "| RequestParams:{" + sb.toString() + "}");
                }
            }
            try {
                Log.d(TAG, "| Response:" + new JSONObject(content));
//            printLogDetail(TAG, "| Response:" + new JSONObject(content));
            } catch (JSONException e) {
                e.printStackTrace();
                Log.d(TAG, "| Response:" + content);
            }
            Log.d(TAG, "----------End:" + duration + "毫秒----------");

        }
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();

//                response.request().url().queryParameterNames().url().pa
    }


    /**
     * 输出完整json，防止一次输出过多时显示不完整问题
     *
     * @param tag
     * @param json
     */
    private void printLogDetail(String tag, String json) {
        try {
            int len = 3500;
            int position = 0;

            while (json.length() - position > len) {
                for (int i = 0; i < json.length() - position - len; i++) {
                    if (json.charAt(position + len + i) == '\n') {
                        Log.v(tag, json.substring(position, position + len + i));
                        position = position + len + i + 1;
                        break;
                    }
                }
            }
            Log.d(tag, json.substring(position, json.length()));
        } catch (Exception e) {
            Log.d(tag, json);
        }

    }

    public static String unicodeToString(String unicode) {
        String str = unicode.replace("0x", "\\");
        StringBuffer string = new StringBuffer();
        String[] hex = str.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int data = Integer.parseInt(hex[i], 16);
            string.append((char) data);
        }
        return string.toString();
    }
}